#/user/bin/env python
# -*- coding:utf-8 -*-
import json
import os

import sys
import time
try:
    import cookielib
except:
    import http.cookiejar as cookielib
import re
import requests
import time

from PIL import Image
from requests import RequestException
import pytesseract
from conf import *
from multiprocessing import Pool


# 使用登录cookie信息
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies')
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie 未能加载")

header = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
#知乎登录
def login_zhihu(phone_num,password) :
    postdata = {
        '_xsrf': get_xsrf(),
        'password': password,
        'captcha': get_captcha(),
        'phone_num': phone_num
    }
    #url 其实还有 email 的 当你在网页输入邮箱形式的用户名提交表单的时候会提交到https://www.zhihu.com/login/email上
    url = "https://www.zhihu.com/login/phone_num"
    print(postdata)
    response = session.post(url,data = postdata,headers = header)
    print(response.text)
    return response

#获取_xsrf码
def get_xsrf() :
    #xsrf码隐藏在网页中的一串匹配码，每次刷新更新，所以需要在网页中抓取
    url = 'https://www.zhihu.com/'
    try :
        response = requests.get(url,headers = header)
        pattern = re.compile('"_xsrf" value="(.*?)"',re.S)
        xsrf = re.findall(pattern,response.text)
        return xsrf[0]
    except RequestException:
        return None

#抓取验证码
def get_captcha():
    t = str(int(time.time()*1000))
    captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + "&type=login"
    try :
        r = session.get(captcha_url, headers=header)
        with open('captcha.jpg', 'wb') as f:
            f.write(r.content)
            f.close()
        try:
            #PIL + pytesseract的方法识别率太低
            #image = Image.open("captcha.jpg")
            #code = pytesseract.image_to_string(image)
            #return code
            pass
        except:
            print(sys.exc_info())   #打印错误原因
            print(u'请到 %s 目录找到captcha.jpg 手动输入' % os.path.abspath('captcha.jpg'))
        captcha = input("please input the captcha\n>")
        return captcha
    except RequestException :
        print("验证码请求错误")
        return None


#获取关注vczh的人
def get_friend(offset):
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',

    }
    data = {
        'include' :'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics',
        'offset' : offset,
        'limit' : 20
    }

    url = 'https://www.zhihu.com/api/v4/members/excited-vczh/followers?'
    response = session.get(url,headers = headers,params = data)
    #print(response.text)
    #assert False,response.text.decode('utf-8')

    pattern = re.compile('"name": "(.*?)".*?"gender":(.*?),.*?"avatar_url": "(.*?)"')
    items = re.findall(pattern,response.text)
    for item in items :
        if item[2] != "https://pic1.zhimg.com/da8e974dc_is.jpg" and item[1] == ' -1':
            yield  {
                'name' : item[0].encode('utf-8').decode('unicode_escape'),    #因为返回的就是一个Unicode 所以我们直接将其反编码就可以了
                'gender' : item[1],
                'image' : item[2]
            }


def main(offset) :
    items = get_friend(offset)

    for item in items :
        print(item)

if __name__ == '__main__':
    start = time.time()
    pool = Pool()
    #如果cookies中有值 则不需要再进行登录
    if session.cookies:
        pool.map(main,[i*20 for i in range(offsets)])
    else:
        response = login_zhihu(username, pwd)
        response = login_zhihu(username, pwd)
        response = json.loads(response.text)
        #如果账号和密码正确 则保存cookie对象
        if response.get('r') == 0:
            session.cookies.save()
            pool.map(main,[i*20 for i in range(offsets)])
    endtime = time.time()

    print('当前运行了' + str(endtime-start))





